# language: zh-CN
# Epic 13: 企业级功能
# 需求ID: REQ-013
# SRS需求: 系统应提供完整的企业级功能支持，包括单点登录(SSO)、LDAP集成、企业级安全、合规审计、高可用性、性能监控、数据治理等企业级特性
# Feature ID: FT-013
# 关联Epic: EP-013 (企业级特性)
# 优先级: 高
# 复杂度: 极高

# 用户故事:
# US-084: 作为企业管理员，我希望集成SSO和LDAP系统，以便统一管理用户身份认证
# US-085: 作为安全管理员，我希望实现企业级安全策略，以便保护敏感数据和系统安全
# US-086: 作为合规官，我希望系统支持审计日志和合规报告，以便满足法规要求
# US-087: 作为运维工程师，我希望实现高可用性和灾备机制，以便确保业务连续性
# US-088: 作为数据管理员，我希望实现数据治理和生命周期管理，以便规范数据使用

# 验收标准:
# - 支持SAML2.0、OAuth2.0、LDAP等企业级身份认证协议
# - 实现细粒度的权限控制和角色管理系统
# - 提供完整的审计日志和合规报告功能
# - 支持多数据中心部署和自动故障转移
# - 实现数据分类、标记和生命周期管理
# - 提供企业级监控、告警和性能分析
# - 支持数据加密、脱敏和隐私保护
# - 满足SOX、GDPR、等保等合规要求

功能: 企业级功能
  作为企业用户
  我希望系统提供企业级功能支持
  以便满足大规模生产环境的需求

  背景:
    假设我是一个企业级应用开发者
    并且我需要支持大规模用户和数据
    并且我需要确保系统的高可用性和安全性
    并且我需要满足企业合规要求

  场景: 单点登录（SSO）集成
    假设我需要集成企业SSO系统
    当我配置SSO集成时:
      """
      @sso_integration({
        provider: 'saml2',
        config: {
          entityId: env('SAML_ENTITY_ID'),
          ssoUrl: env('SAML_SSO_URL'),
          sloUrl: env('SAML_SLO_URL'),
          certificate: env('SAML_CERTIFICATE'),
          privateKey: env('SAML_PRIVATE_KEY'),
          nameIdFormat: 'urn:oasis:names:tc:SAML:2.0:nameid-format:emailAddress'
        },
        attributeMapping: {
          email: 'http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress',
          name: 'http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name',
          department: 'http://schemas.xmlsoap.org/ws/2005/05/identity/claims/department',
          role: 'http://schemas.xmlsoap.org/ws/2005/05/identity/claims/role'
        },
        features: {
          autoProvisioning: true,
          roleMapping: true,
          sessionManagement: true,
          auditLogging: true
        }
      })
      
      entity SsoUser {
        id: string @primary
        email: string @required @unique
        name: string @required
        department: string @optional
        
        // SSO信息
        ssoProvider: string @required
        ssoSubject: string @required @unique
        nameId: string @required
        
        // 企业信息
        employeeId: string @optional
        organizationUnit: string @optional
        
        // 会话管理
        sessionId: string @optional
        lastLogin: datetime @optional
        sessionExpiresAt: datetime @optional
        
        // 状态
        isActive: boolean @default(true)
        isProvisioned: boolean @default(false)
        
        // 关联
        roles: Role[] @many_to_many
        
        createdAt: datetime @auto_now_add
        updatedAt: datetime @auto_now
        
        @@index([ssoProvider, ssoSubject])
      }
      
      entity SsoSession {
        id: string @primary
        sessionIndex: string @required @unique
        nameId: string @required
        
        // 会话信息
        userId: string @foreign_key('SsoUser')
        ipAddress: string @required
        userAgent: string @required
        
        // 时间信息
        authenticatedAt: datetime @required
        expiresAt: datetime @required
        lastActivity: datetime @required
        
        // 状态
        isActive: boolean @default(true)
        
        createdAt: datetime @auto_now_add
        updatedAt: datetime @auto_now
      }
      
      service SsoService {
        @saml_integration
        async handleSamlResponse(samlResponse: string): Promise<{ user: SsoUser, token: string }> {
          const assertion = await this.validateSamlResponse(samlResponse);
          const attributes = this.extractAttributes(assertion);
          
          let user = await SsoUser.findOne({ ssoSubject: assertion.subject });
          
          if (!user && this.config.autoProvisioning) {
            user = await this.provisionUser(attributes, assertion);
          } else if (user) {
            user = await this.updateUserAttributes(user, attributes);
          }
          
          if (!user) {
            throw new SsoAuthenticationError('User not found and auto-provisioning disabled');
          }
          
          // 创建会话
          const session = await SsoSession.create({
            sessionIndex: assertion.sessionIndex,
            nameId: assertion.nameId,
            userId: user.id,
            ipAddress: this.getClientIp(),
            userAgent: this.getUserAgent(),
            authenticatedAt: new Date(),
            expiresAt: new Date(Date.now() + 8 * 60 * 60 * 1000), // 8小时
            lastActivity: new Date()
          });
          
          // 更新用户会话信息
          await SsoUser.update({ id: user.id }, {
            sessionId: session.id,
            lastLogin: new Date(),
            sessionExpiresAt: session.expiresAt
          });
          
          const token = this.generateJwtToken(user, session);
          return { user, token };
        }
        
        @saml_integration
        async handleSingleLogout(logoutRequest: string): Promise<void> {
          const request = await this.validateLogoutRequest(logoutRequest);
          
          // 查找并终止会话
          const session = await SsoSession.findOne({ 
            sessionIndex: request.sessionIndex,
            nameId: request.nameId,
            isActive: true
          });
          
          if (session) {
            await SsoSession.update({ id: session.id }, { isActive: false });
            await SsoUser.update({ id: session.userId }, { 
              sessionId: null,
              sessionExpiresAt: null
            });
            
            // 记录审计日志
            await this.logAuditEvent('sso.logout', {
              userId: session.userId,
              sessionId: session.id,
              reason: 'single_logout'
            });
          }
        }
      }
      """
    那么应该生成SSO集成代码:
      """
      import saml2 from 'saml2-js';
      import crypto from 'crypto';
      
      export class SsoService {
        private samlProvider: saml2.ServiceProvider;
        private identityProvider: saml2.IdentityProvider;
        
        constructor() {
          this.samlProvider = new saml2.ServiceProvider({
            entity_id: process.env.SAML_ENTITY_ID!,
            private_key: process.env.SAML_PRIVATE_KEY!,
            certificate: process.env.SAML_CERTIFICATE!,
            assert_endpoint: `${process.env.APP_URL}/auth/saml/acs`,
            force_authn: false,
            auth_context: {
              comparison: 'exact',
              class_refs: ['urn:oasis:names:tc:SAML:1.0:am:password']
            },
            nameid_format: 'urn:oasis:names:tc:SAML:2.0:nameid-format:emailAddress',
            sign_get_request: false,
            allow_unencrypted_assertion: true
          });
          
          this.identityProvider = new saml2.IdentityProvider({
            sso_login_url: process.env.SAML_SSO_URL!,
            sso_logout_url: process.env.SAML_SLO_URL!,
            certificates: [process.env.SAML_IDP_CERTIFICATE!]
          });
        }
        
        async generateLoginUrl(relayState?: string): Promise<string> {
          return new Promise((resolve, reject) => {
            this.samlProvider.create_login_request_url(
              this.identityProvider,
              { relay_state: relayState },
              (err, loginUrl) => {
                if (err) reject(err);
                else resolve(loginUrl);
              }
            );
          });
        }
        
        async handleSamlResponse(samlResponse: string, relayState?: string): Promise<{ user: SsoUser, token: string }> {
          try {
            const assertion = await this.validateSamlAssertion(samlResponse);
            
            const attributes = {
              email: assertion.user.attributes.email?.[0],
              name: assertion.user.attributes.name?.[0],
              department: assertion.user.attributes.department?.[0],
              role: assertion.user.attributes.role?.[0]
            };
            
            let user = await SsoUser.findOne({ 
              ssoSubject: assertion.user.name_id 
            });
            
            if (!user) {
              if (!this.config.autoProvisioning) {
                throw new SsoAuthenticationError('User not found and auto-provisioning is disabled');
              }
              
              user = await SsoUser.create({
                email: attributes.email,
                name: attributes.name,
                department: attributes.department,
                ssoProvider: 'saml2',
                ssoSubject: assertion.user.name_id,
                nameId: assertion.user.name_id,
                isProvisioned: true,
                isActive: true
              });
              
              // 分配角色
              if (attributes.role && this.config.roleMapping) {
                await this.assignRolesByMapping(user.id, attributes.role);
              }
            } else {
              // 更新用户属性
              await SsoUser.update({ id: user.id }, {
                name: attributes.name,
                department: attributes.department,
                lastLogin: new Date()
              });
            }
            
            // 创建会话
            const session = await SsoSession.create({
              sessionIndex: assertion.user.session_index || crypto.randomUUID(),
              nameId: assertion.user.name_id,
              userId: user.id,
              ipAddress: this.getClientIp(),
              userAgent: this.getUserAgent(),
              authenticatedAt: new Date(),
              expiresAt: new Date(Date.now() + 8 * 60 * 60 * 1000),
              lastActivity: new Date(),
              isActive: true
            });
            
            // 更新用户会话信息
            await SsoUser.update({ id: user.id }, {
              sessionId: session.id,
              sessionExpiresAt: session.expiresAt
            });
            
            // 记录审计日志
            await this.logAuditEvent('sso.login', {
              userId: user.id,
              sessionId: session.id,
              ipAddress: this.getClientIp(),
              userAgent: this.getUserAgent()
            });
            
            const token = this.generateJwtToken(user, session);
            return { user, token };
          } catch (error) {
            await this.logAuditEvent('sso.login_failed', {
              error: error.message,
              ipAddress: this.getClientIp()
            });
            throw new SsoAuthenticationError('SAML authentication failed', error);
          }
        }
        
        private async validateSamlAssertion(samlResponse: string): Promise<any> {
          return new Promise((resolve, reject) => {
            this.samlProvider.post_assert(
              this.identityProvider,
              { request_body: { SAMLResponse: samlResponse } },
              (err, samlResponse) => {
                if (err) reject(err);
                else resolve(samlResponse);
              }
            );
          });
        }
        
        private async assignRolesByMapping(userId: string, roleName: string): Promise<void> {
          const roleMapping = {
            'admin': ['administrator'],
            'manager': ['manager', 'user'],
            'user': ['user']
          };
          
          const roleNames = roleMapping[roleName.toLowerCase()] || ['user'];
          const roles = await Role.findMany({ name: { in: roleNames } });
          
          if (roles.length > 0) {
            await SsoUser.update({ id: userId }, {
              roles: { connect: roles.map(role => ({ id: role.id })) }
            });
          }
        }
      }
      """
    并且应该支持自动用户配置
    并且应该支持角色映射
    并且应该支持会话管理
    并且应该记录审计日志

  场景: 高级权限控制（RBAC）
    假设我需要实现基于角色的访问控制
    当我配置RBAC系统时:
      """
      @rbac_system({
        hierarchical: true,
        inheritance: true,
        dynamicPermissions: true,
        contextualAccess: true,
        auditTrail: true
      })
      
      entity Role {
        id: string @primary
        name: string @required @unique
        displayName: string @required
        description: string @optional
        
        // 层级关系
        parentId: string @foreign_key('Role') @optional
        level: number @required @default(0)
        path: string @required // 用于层级查询
        
        // 权限
        permissions: Permission[] @many_to_many
        
        // 状态
        isActive: boolean @default(true)
        isSystem: boolean @default(false) // 系统角色不可删除
        
        // 关联
        users: User[] @many_to_many
        children: Role[] @one_to_many('parentId')
        parent: Role @belongs_to('parentId')
        
        createdAt: datetime @auto_now_add
        updatedAt: datetime @auto_now
        
        @@index([path])
        @@index([level])
      }
      
      entity Permission {
        id: string @primary
        name: string @required @unique
        displayName: string @required
        description: string @optional
        
        // 权限分类
        resource: string @required // 资源类型
        action: string @required // 操作类型
        scope: PermissionScope @required
        
        // 条件权限
        conditions: json @optional // 动态权限条件
        
        // 状态
        isActive: boolean @default(true)
        isSystem: boolean @default(false)
        
        // 关联
        roles: Role[] @many_to_many
        
        createdAt: datetime @auto_now_add
        updatedAt: datetime @auto_now
        
        @@unique([resource, action, scope])
        @@index([resource])
        @@index([action])
      }
      
      enum PermissionScope {
        GLOBAL = 'global' // 全局权限
        ORGANIZATION = 'organization' // 组织权限
        DEPARTMENT = 'department' // 部门权限
        TEAM = 'team' // 团队权限
        PERSONAL = 'personal' // 个人权限
      }
      
      entity AccessLog {
        id: string @primary
        userId: string @foreign_key('User')
        resource: string @required
        action: string @required
        
        // 访问结果
        result: AccessResult @required
        reason: string @optional
        
        // 上下文信息
        ipAddress: string @required
        userAgent: string @required
        requestId: string @optional
        
        // 权限信息
        appliedRoles: string[] @required
        appliedPermissions: string[] @required
        
        // 时间信息
        accessedAt: datetime @auto_now_add
        
        @@index([userId, accessedAt])
        @@index([resource, action])
        @@index([result])
      }
      
      enum AccessResult {
        GRANTED = 'granted'
        DENIED = 'denied'
        ERROR = 'error'
      }
      
      service RbacService {
        async checkPermission(
          userId: string, 
          resource: string, 
          action: string, 
          context?: AccessContext
        ): Promise<boolean> {
          try {
            const user = await User.findById(userId, {
              include: {
                roles: {
                  include: {
                    permissions: true,
                    parent: {
                      include: { permissions: true }
                    }
                  }
                }
              }
            });
            
            if (!user || !user.isActive) {
              await this.logAccess(userId, resource, action, AccessResult.DENIED, 'User not found or inactive');
              return false;
            }
            
            // 收集所有权限（包括继承的权限）
            const allPermissions = this.collectAllPermissions(user.roles);
            
            // 检查权限
            const hasPermission = allPermissions.some(permission => 
              permission.resource === resource && 
              permission.action === action &&
              permission.isActive &&
              this.evaluateConditions(permission.conditions, context)
            );
            
            // 记录访问日志
            await this.logAccess(
              userId, 
              resource, 
              action, 
              hasPermission ? AccessResult.GRANTED : AccessResult.DENIED,
              hasPermission ? 'Permission granted' : 'Permission denied',
              user.roles.map(r => r.name),
              allPermissions.map(p => p.name)
            );
            
            return hasPermission;
          } catch (error) {
            await this.logAccess(userId, resource, action, AccessResult.ERROR, error.message);
            throw new RbacError('Permission check failed', error);
          }
        }
        
        async assignRole(userId: string, roleId: string): Promise<void> {
          const user = await User.findById(userId);
          const role = await Role.findById(roleId);
          
          if (!user || !role) {
            throw new RbacError('User or role not found');
          }
          
          if (!role.isActive) {
            throw new RbacError('Cannot assign inactive role');
          }
          
          await User.update({ id: userId }, {
            roles: { connect: { id: roleId } }
          });
          
          await this.logAuditEvent('role.assigned', {
            userId,
            roleId,
            roleName: role.name
          });
        }
        
        async createRole(data: CreateRoleData): Promise<Role> {
          // 计算层级路径
          let path = data.name;
          let level = 0;
          
          if (data.parentId) {
            const parent = await Role.findById(data.parentId);
            if (!parent) {
              throw new RbacError('Parent role not found');
            }
            path = `${parent.path}/${data.name}`;
            level = parent.level + 1;
          }
          
          const role = await Role.create({
            name: data.name,
            displayName: data.displayName,
            description: data.description,
            parentId: data.parentId,
            level,
            path,
            isActive: true
          });
          
          // 分配权限
          if (data.permissionIds && data.permissionIds.length > 0) {
            await Role.update({ id: role.id }, {
              permissions: {
                connect: data.permissionIds.map(id => ({ id }))
              }
            });
          }
          
          await this.logAuditEvent('role.created', {
            roleId: role.id,
            roleName: role.name,
            parentId: data.parentId
          });
          
          return role;
        }
        
        private collectAllPermissions(roles: Role[]): Permission[] {
          const permissions = new Map<string, Permission>();
          
          const addPermissions = (role: Role) => {
            // 添加直接权限
            role.permissions?.forEach(permission => {
              permissions.set(permission.id, permission);
            });
            
            // 添加继承权限
            if (role.parent) {
              addPermissions(role.parent);
            }
          };
          
          roles.forEach(addPermissions);
          return Array.from(permissions.values());
        }
        
        private evaluateConditions(conditions: any, context?: AccessContext): boolean {
          if (!conditions || !context) return true;
          
          // 实现条件评估逻辑
          // 例如：时间限制、IP限制、资源所有权等
          if (conditions.timeRestriction) {
            const now = new Date();
            const start = new Date(conditions.timeRestriction.start);
            const end = new Date(conditions.timeRestriction.end);
            if (now < start || now > end) return false;
          }
          
          if (conditions.ipRestriction) {
            const allowedIps = conditions.ipRestriction.allowed || [];
            if (allowedIps.length > 0 && !allowedIps.includes(context.ipAddress)) {
              return false;
            }
          }
          
          if (conditions.resourceOwnership && context.resourceOwnerId) {
            return context.userId === context.resourceOwnerId;
          }
          
          return true;
        }
      }
      """
    那么应该生成RBAC系统代码:
      """
      export class RbacService {
        private permissionCache = new Map<string, Permission[]>();
        private cacheExpiry = 5 * 60 * 1000; // 5分钟缓存
        
        async checkPermission(
          userId: string,
          resource: string,
          action: string,
          context?: AccessContext
        ): Promise<boolean> {
          const startTime = Date.now();
          
          try {
            // 检查用户状态
            const user = await this.getUserWithRoles(userId);
            if (!user?.isActive) {
              await this.logAccess(userId, resource, action, AccessResult.DENIED, 'User inactive');
              return false;
            }
            
            // 获取用户所有权限（包括缓存）
            const permissions = await this.getUserPermissions(userId, user.roles);
            
            // 检查权限匹配
            const matchingPermissions = permissions.filter(p => 
              p.resource === resource && 
              p.action === action && 
              p.isActive
            );
            
            if (matchingPermissions.length === 0) {
              await this.logAccess(userId, resource, action, AccessResult.DENIED, 'No matching permission');
              return false;
            }
            
            // 评估条件权限
            const hasValidPermission = matchingPermissions.some(permission => 
              this.evaluatePermissionConditions(permission, context)
            );
            
            const result = hasValidPermission ? AccessResult.GRANTED : AccessResult.DENIED;
            const reason = hasValidPermission ? 'Permission granted' : 'Conditions not met';
            
            await this.logAccess(
              userId,
              resource,
              action,
              result,
              reason,
              user.roles.map(r => r.name),
              matchingPermissions.map(p => p.name)
            );
            
            // 记录性能指标
            const duration = Date.now() - startTime;
            await this.recordMetric('rbac.permission_check_duration', duration);
            
            return hasValidPermission;
          } catch (error) {
            await this.logAccess(userId, resource, action, AccessResult.ERROR, error.message);
            throw new RbacError(`Permission check failed: ${error.message}`, error);
          }
        }
        
        async getUserPermissions(userId: string, roles?: Role[]): Promise<Permission[]> {
          const cacheKey = `user_permissions_${userId}`;
          const cached = this.permissionCache.get(cacheKey);
          
          if (cached && this.isCacheValid(cacheKey)) {
            return cached;
          }
          
          if (!roles) {
            const user = await this.getUserWithRoles(userId);
            roles = user?.roles || [];
          }
          
          const permissions = new Map<string, Permission>();
          
          // 递归收集权限（包括角色继承）
          const collectPermissions = async (role: Role) => {
            // 添加角色直接权限
            const roleWithPermissions = await Role.findById(role.id, {
              include: { permissions: true, parent: true }
            });
            
            roleWithPermissions?.permissions?.forEach(permission => {
              permissions.set(permission.id, permission);
            });
            
            // 递归处理父角色
            if (roleWithPermissions?.parent) {
              await collectPermissions(roleWithPermissions.parent);
            }
          };
          
          // 处理所有用户角色
          for (const role of roles) {
            await collectPermissions(role);
          }
          
          const result = Array.from(permissions.values());
          
          // 缓存结果
          this.permissionCache.set(cacheKey, result);
          setTimeout(() => this.permissionCache.delete(cacheKey), this.cacheExpiry);
          
          return result;
        }
        
        async createHierarchicalRole(data: CreateRoleData): Promise<Role> {
          const transaction = await this.startTransaction();
          
          try {
            // 验证父角色
            let parentRole: Role | null = null;
            if (data.parentId) {
              parentRole = await Role.findById(data.parentId);
              if (!parentRole) {
                throw new RbacError('Parent role not found');
              }
              if (!parentRole.isActive) {
                throw new RbacError('Parent role is inactive');
              }
            }
            
            // 计算层级信息
            const level = parentRole ? parentRole.level + 1 : 0;
            const path = parentRole ? `${parentRole.path}/${data.name}` : data.name;
            
            // 验证层级深度
            if (level > 10) {
              throw new RbacError('Role hierarchy too deep (max 10 levels)');
            }
            
            // 创建角色
            const role = await Role.create({
              name: data.name,
              displayName: data.displayName,
              description: data.description,
              parentId: data.parentId,
              level,
              path,
              isActive: true,
              isSystem: false
            }, { transaction });
            
            // 分配权限
            if (data.permissionIds?.length) {
              const permissions = await Permission.findMany({
                id: { in: data.permissionIds },
                isActive: true
              });
              
              if (permissions.length !== data.permissionIds.length) {
                throw new RbacError('Some permissions not found or inactive');
              }
              
              await role.permissions.connect(permissions.map(p => ({ id: p.id })));
            }
            
            await transaction.commit();
            
            // 清除相关缓存
            this.clearPermissionCache();
            
            // 记录审计日志
            await this.logAuditEvent('role.created', {
              roleId: role.id,
              roleName: role.name,
              parentId: data.parentId,
              level,
              path
            });
            
            return role;
          } catch (error) {
            await transaction.rollback();
            throw error;
          }
        }
        
        private evaluatePermissionConditions(permission: Permission, context?: AccessContext): boolean {
          if (!permission.conditions || !context) return true;
          
          const conditions = permission.conditions as any;
          
          // 时间限制
          if (conditions.timeWindow) {
            const now = new Date();
            const dayOfWeek = now.getDay();
            const hour = now.getHours();
            
            if (conditions.timeWindow.days && !conditions.timeWindow.days.includes(dayOfWeek)) {
              return false;
            }
            
            if (conditions.timeWindow.hours) {
              const { start, end } = conditions.timeWindow.hours;
              if (hour < start || hour > end) {
                return false;
              }
            }
          }
          
          // IP地址限制
          if (conditions.ipRestriction) {
            const { allowed, denied } = conditions.ipRestriction;
            
            if (denied?.includes(context.ipAddress)) {
              return false;
            }
            
            if (allowed?.length && !allowed.includes(context.ipAddress)) {
              return false;
            }
          }
          
          // 资源所有权
          if (conditions.resourceOwnership) {
            if (!context.resourceOwnerId || context.userId !== context.resourceOwnerId) {
              return false;
            }
          }
          
          // 部门限制
          if (conditions.departmentRestriction) {
            if (!context.userDepartment || 
                !conditions.departmentRestriction.includes(context.userDepartment)) {
              return false;
            }
          }
          
          return true;
        }
        
        private async logAccess(
          userId: string,
          resource: string,
          action: string,
          result: AccessResult,
          reason?: string,
          roles?: string[],
          permissions?: string[]
        ): Promise<void> {
          await AccessLog.create({
            userId,
            resource,
            action,
            result,
            reason,
            ipAddress: this.getClientIp(),
            userAgent: this.getUserAgent(),
            requestId: this.getRequestId(),
            appliedRoles: roles || [],
            appliedPermissions: permissions || []
          });
        }
      }
      """
    并且应该支持角色继承
    并且应该支持条件权限
    并且应该提供权限缓存
    并且应该记录访问日志

  场景: 数据加密和脱敏
    假设我需要实现数据加密和脱敏
    当我配置数据保护时:
      """
      @data_protection({
        encryption: {
          algorithm: 'AES-256-GCM',
          keyRotation: true,
          keyRotationInterval: '90d'
        },
        masking: {
          enabled: true,
          rules: 'gdpr_compliant'
        },
        auditTrail: true,
        compliance: ['GDPR', 'CCPA', 'SOX']
      })
      
      entity Customer {
        id: string @primary
        
        // 加密字段
        email: string @required @encrypted @pii
        phone: string @optional @encrypted @pii
        ssn: string @optional @encrypted @sensitive
        
        // 脱敏字段
        name: string @required @masked('partial') @pii
        address: string @optional @masked('full') @pii
        
        // 普通字段
        customerNumber: string @required @unique
        status: CustomerStatus @required
        
        // 审计字段
        dataClassification: DataClassification @required
        lastAccessedAt: datetime @optional
        accessCount: number @default(0)
        
        createdAt: datetime @auto_now_add
        updatedAt: datetime @auto_now
        
        @@index([customerNumber])
      }
      
      enum DataClassification {
        PUBLIC = 'public'
        INTERNAL = 'internal'
        CONFIDENTIAL = 'confidential'
        RESTRICTED = 'restricted'
      }
      
      entity DataAccessLog {
        id: string @primary
        userId: string @foreign_key('User')
        resourceType: string @required
        resourceId: string @required
        
        // 访问信息
        action: DataAction @required
        fieldsAccessed: string[] @required
        
        // 数据分类
        dataClassification: DataClassification @required
        sensitiveFieldsAccessed: string[] @required
        
        // 上下文
        purpose: string @required // 访问目的
        legalBasis: string @optional // 法律依据
        
        // 技术信息
        ipAddress: string @required
        userAgent: string @required
        sessionId: string @required
        
        accessedAt: datetime @auto_now_add
        
        @@index([userId, accessedAt])
        @@index([resourceType, resourceId])
        @@index([dataClassification])
      }
      
      enum DataAction {
        READ = 'read'
        create = 'create'
        update = 'update'
        delete = 'delete'
        export = 'export'
        print = 'print'
      }
      
      entity EncryptionKey {
        id: string @primary
        keyId: string @required @unique
        algorithm: string @required
        
        // 密钥信息
        encryptedKey: string @required
        keyVersion: number @required
        
        // 状态
        isActive: boolean @default(true)
        isPrimary: boolean @default(false)
        
        // 时间信息
        createdAt: datetime @auto_now_add
        expiresAt: datetime @required
        rotatedAt: datetime @optional
        
        @@index([keyId, keyVersion])
        @@index([isActive, isPrimary])
      }
      
      service DataProtectionService {
        async encryptSensitiveData(data: any, classification: DataClassification): Promise<any> {
          const encryptedData = { ...data };
          const fieldsToEncrypt = this.getEncryptionFields(data);
          
          for (const field of fieldsToEncrypt) {
            if (data[field] !== null && data[field] !== undefined) {
              const encrypted = await this.encryptField(data[field], field, classification);
              encryptedData[field] = encrypted;
            }
          }
          
          return encryptedData;
        }
        
        async decryptSensitiveData(
          encryptedData: any, 
          userId: string, 
          purpose: string,
          fieldsRequested?: string[]
        ): Promise<any> {
          // 检查访问权限
          const hasAccess = await this.checkDataAccess(userId, encryptedData.id, purpose);
          if (!hasAccess) {
            throw new DataAccessDeniedError('Access to sensitive data denied');
          }
          
          const decryptedData = { ...encryptedData };
          const fieldsToDecrypt = fieldsRequested || this.getEncryptionFields(encryptedData);
          const accessedFields: string[] = [];
          const sensitiveFields: string[] = [];
          
          for (const field of fieldsToDecrypt) {
            if (encryptedData[field] && this.isEncryptedField(field)) {
              try {
                const decrypted = await this.decryptField(encryptedData[field], field);
                decryptedData[field] = decrypted;
                accessedFields.push(field);
                
                if (this.isSensitiveField(field)) {
                  sensitiveFields.push(field);
                }
              } catch (error) {
                // 解密失败，保持原值或设为null
                decryptedData[field] = null;
              }
            }
          }
          
          // 记录数据访问日志
          await this.logDataAccess({
            userId,
            resourceType: 'Customer',
            resourceId: encryptedData.id,
            action: DataAction.read,
            fieldsAccessed: accessedFields,
            sensitiveFieldsAccessed: sensitiveFields,
            dataClassification: encryptedData.dataClassification || DataClassification.CONFIDENTIAL,
            purpose,
            ipAddress: this.getClientIp(),
            userAgent: this.getUserAgent(),
            sessionId: this.getSessionId()
          });
          
          return decryptedData;
        }
        
        async maskSensitiveData(data: any, userRole: string): Promise<any> {
          const maskedData = { ...data };
          const maskingRules = this.getMaskingRules(userRole);
          
          for (const [field, rule] of Object.entries(maskingRules)) {
            if (data[field] !== null && data[field] !== undefined) {
              maskedData[field] = this.applyMaskingRule(data[field], rule);
            }
          }
          
          return maskedData;
        }
        
        async rotateEncryptionKeys(): Promise<void> {
          const currentKey = await EncryptionKey.findOne({ 
            isActive: true, 
            isPrimary: true 
          });
          
          if (!currentKey) {
            throw new EncryptionError('No primary encryption key found');
          }
          
          // 检查是否需要轮换
          const keyAge = Date.now() - currentKey.createdAt.getTime();
          const rotationInterval = 90 * 24 * 60 * 60 * 1000; // 90天
          
          if (keyAge < rotationInterval) {
            return; // 还不需要轮换
          }
          
          const transaction = await this.startTransaction();
          
          try {
            // 生成新密钥
            const newKey = await this.generateEncryptionKey();
            
            // 创建新密钥记录
            const newKeyRecord = await EncryptionKey.create({
              keyId: newKey.id,
              algorithm: 'AES-256-GCM',
              encryptedKey: await this.encryptMasterKey(newKey.key),
              keyVersion: currentKey.keyVersion + 1,
              isActive: true,
              isPrimary: true,
              expiresAt: new Date(Date.now() + rotationInterval)
            }, { transaction });
            
            // 更新旧密钥状态
            await EncryptionKey.update(
              { id: currentKey.id },
              { 
                isPrimary: false,
                rotatedAt: new Date()
              },
              { transaction }
            );
            
            // 重新加密敏感数据（异步处理）
            this.scheduleDataReencryption(currentKey.keyId, newKeyRecord.keyId);
            
            await transaction.commit();
            
            await this.logAuditEvent('encryption.key_rotated', {
              oldKeyId: currentKey.keyId,
              newKeyId: newKeyRecord.keyId,
              keyVersion: newKeyRecord.keyVersion
            });
          } catch (error) {
            await transaction.rollback();
            throw new EncryptionError('Key rotation failed', error);
          }
        }
        
        private applyMaskingRule(value: string, rule: any): string {
          switch (rule.type) {
            case 'partial':
              if (value.includes('@')) {
                // Email masking
                const [local, domain] = value.split('@');
                const maskedLocal = local.charAt(0) + '*'.repeat(local.length - 2) + local.charAt(local.length - 1);
                return `${maskedLocal}@${domain}`;
              } else {
                // General partial masking
                const visibleChars = Math.min(rule.visibleChars || 2, value.length);
                return value.substring(0, visibleChars) + '*'.repeat(value.length - visibleChars);
              }
            
            case 'full':
              return '*'.repeat(value.length);
            
            case 'phone':
              // Phone number masking: +1 (555) ***-****
              return value.replace(/(\d{3})(\d{3})(\d{4})/, '$1-***-****');
            
            case 'ssn':
              // SSN masking: ***-**-1234
              return value.replace(/(\d{3})(\d{2})(\d{4})/, '***-**-$3');
            
            default:
              return value;
          }
        }
      }
      """
    那么应该生成数据保护代码:
      """
      import crypto from 'crypto';
      import { KMS } from 'aws-sdk';
      
      export class DataProtectionService {
        private kms: KMS;
        private encryptionCache = new Map<string, any>();
        
        constructor() {
          this.kms = new KMS({
            region: process.env.AWS_REGION,
            accessKeyId: process.env.AWS_ACCESS_KEY_ID,
            secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY
          });
        }
        
        async encryptField(value: string, fieldName: string, classification: DataClassification): Promise<string> {
          try {
            const key = await this.getCurrentEncryptionKey();
            const iv = crypto.randomBytes(16);
            
            const cipher = crypto.createCipher('aes-256-gcm', key.key);
            cipher.setAAD(Buffer.from(fieldName)); // 使用字段名作为附加认证数据
            
            let encrypted = cipher.update(value, 'utf8', 'hex');
            encrypted += cipher.final('hex');
            
            const authTag = cipher.getAuthTag();
            
            // 组合加密结果
            const result = {
              data: encrypted,
              iv: iv.toString('hex'),
              authTag: authTag.toString('hex'),
              keyId: key.keyId,
              keyVersion: key.keyVersion,
              algorithm: 'AES-256-GCM'
            };
            
            return Buffer.from(JSON.stringify(result)).toString('base64');
          } catch (error) {
            throw new EncryptionError(`Failed to encrypt field ${fieldName}`, error);
          }
        }
        
        async decryptField(encryptedValue: string, fieldName: string): Promise<string> {
          try {
            const encryptedData = JSON.parse(Buffer.from(encryptedValue, 'base64').toString());
            
            const key = await this.getEncryptionKey(encryptedData.keyId, encryptedData.keyVersion);
            if (!key) {
              throw new EncryptionError('Encryption key not found');
            }
            
            const decipher = crypto.createDecipher('aes-256-gcm', key.key);
            decipher.setAAD(Buffer.from(fieldName));
            decipher.setAuthTag(Buffer.from(encryptedData.authTag, 'hex'));
            
            let decrypted = decipher.update(encryptedData.data, 'hex', 'utf8');
            decrypted += decipher.final('utf8');
            
            return decrypted;
          } catch (error) {
            throw new EncryptionError(`Failed to decrypt field ${fieldName}`, error);
          }
        }
        
        async maskDataForUser(data: any, userId: string): Promise<any> {
          const user = await User.findById(userId, { include: { roles: true } });
          if (!user) {
            throw new DataAccessError('User not found');
          }
          
          const userRoles = user.roles.map(r => r.name);
          const maskingLevel = this.determineMaskingLevel(userRoles);
          
          const maskedData = { ...data };
          
          // 根据用户角色应用不同的脱敏规则
          const maskingRules = {
            admin: {}, // 管理员不脱敏
            manager: {
              ssn: { type: 'ssn' },
              phone: { type: 'phone' }
            },
            user: {
              email: { type: 'partial', visibleChars: 3 },
              phone: { type: 'phone' },
              ssn: { type: 'full' },
              address: { type: 'full' }
            },
            guest: {
              email: { type: 'full' },
              phone: { type: 'full' },
              ssn: { type: 'full' },
              address: { type: 'full' },
              name: { type: 'partial', visibleChars: 1 }
            }
          };
          
          const rules = maskingRules[maskingLevel] || maskingRules.guest;
          
          for (const [field, rule] of Object.entries(rules)) {
            if (data[field] !== null && data[field] !== undefined) {
              maskedData[field] = this.applyMaskingRule(data[field], rule);
            }
          }
          
          return maskedData;
        }
        
        async checkDataAccess(userId: string, resourceId: string, purpose: string): Promise<boolean> {
          // 检查用户权限
          const hasPermission = await this.rbacService.checkPermission(
            userId,
            'customer_data',
            'read',
            { purpose }
          );
          
          if (!hasPermission) {
            return false;
          }
          
          // 检查访问频率限制
          const recentAccess = await DataAccessLog.count({
            userId,
            resourceId,
            accessedAt: {
              gte: new Date(Date.now() - 60 * 60 * 1000) // 最近1小时
            }
          });
          
          if (recentAccess > 10) { // 每小时最多10次访问
            await this.logSecurityEvent('excessive_data_access', {
              userId,
              resourceId,
              accessCount: recentAccess
            });
            return false;
          }
          
          return true;
        }
        
        async generateComplianceReport(startDate: Date, endDate: Date): Promise<ComplianceReport> {
          const accessLogs = await DataAccessLog.findMany({
            accessedAt: {
              gte: startDate,
              lte: endDate
            }
          });
          
          const report = {
            period: { start: startDate, end: endDate },
            totalAccesses: accessLogs.length,
            uniqueUsers: new Set(accessLogs.map(log => log.userId)).size,
            dataClassificationBreakdown: this.groupBy(accessLogs, 'dataClassification'),
            actionBreakdown: this.groupBy(accessLogs, 'action'),
            sensitiveDataAccesses: accessLogs.filter(log => log.sensitiveFieldsAccessed.length > 0).length,
            complianceViolations: await this.detectComplianceViolations(accessLogs),
            recommendations: await this.generateComplianceRecommendations(accessLogs)
          };
          
          return report;
        }
        
        private determineMaskingLevel(roles: string[]): string {
          if (roles.includes('admin') || roles.includes('system_admin')) {
            return 'admin';
          }
          if (roles.includes('manager') || roles.includes('supervisor')) {
            return 'manager';
          }
          if (roles.includes('user') || roles.includes('employee')) {
            return 'user';
          }
          return 'guest';
        }
        
        private async detectComplianceViolations(accessLogs: DataAccessLog[]): Promise<any[]> {
          const violations = [];
          
          // 检测异常访问模式
          const userAccessCounts = this.groupBy(accessLogs, 'userId');
          for (const [userId, count] of Object.entries(userAccessCounts)) {
            if (count > 100) { // 单用户访问过多
              violations.push({
                type: 'excessive_access',
                userId,
                count,
                severity: 'medium'
              });
            }
          }
          
          // 检测非工作时间访问
          const afterHoursAccess = accessLogs.filter(log => {
            const hour = log.accessedAt.getHours();
            return hour < 8 || hour > 18; // 非工作时间
          });
          
          if (afterHoursAccess.length > 0) {
            violations.push({
              type: 'after_hours_access',
              count: afterHoursAccess.length,
              severity: 'low'
            });
          }
          
          return violations;
        }
      }
      """
    并且应该支持字段级加密
    并且应该支持数据脱敏
    并且应该支持密钥轮换
    并且应该记录访问审计

  场景: 合规性报告
    假设我需要生成合规性报告
    当我配置合规性监控时:
      """
      @compliance_monitoring({
        frameworks: ['GDPR', 'CCPA', 'SOX', 'HIPAA'],
        reportingSchedule: 'monthly',
        alertThresholds: {
          dataAccess: 1000,
          failedLogins: 50,
          privilegedAccess: 100
        },
        retention: {
          auditLogs: '7y',
          accessLogs: '3y',
          securityLogs: '5y'
        }
      })
      
      entity ComplianceReport {
        id: string @primary
        framework: ComplianceFramework @required
        reportType: ReportType @required
        
        // 报告期间
        startDate: datetime @required
        endDate: datetime @required
        
        // 报告内容
        summary: json @required
        findings: json @required
        violations: json @required
        recommendations: json @required
        
        // 状态
        status: ReportStatus @required
        generatedBy: string @foreign_key('User')
        reviewedBy: string @foreign_key('User') @optional
        approvedBy: string @foreign_key('User') @optional
        
        // 文件信息
        reportFile: string @optional // 报告文件路径
        fileSize: number @optional
        fileHash: string @optional
        
        createdAt: datetime @auto_now_add
        updatedAt: datetime @auto_now
        
        @@index([framework, reportType])
        @@index([startDate, endDate])
      }
      
      enum ComplianceFramework {
        GDPR = 'gdpr'
        CCPA = 'ccpa'
        SOX = 'sox'
        HIPAA = 'hipaa'
        PCI_DSS = 'pci_dss'
        ISO27001 = 'iso27001'
      }
      
      enum ReportType {
        AUDIT = 'audit'
        SECURITY = 'security'
        DATA_PROTECTION = 'data_protection'
        ACCESS_CONTROL = 'access_control'
        INCIDENT = 'incident'
      }
      
      enum ReportStatus {
        GENERATING = 'generating'
        DRAFT = 'draft'
        REVIEW = 'review'
        APPROVED = 'approved'
        PUBLISHED = 'published'
      }
      
      service ComplianceService {
        async generateGdprReport(startDate: Date, endDate: Date): Promise<ComplianceReport> {
          const reportData = {
            dataProcessingActivities: await this.getDataProcessingActivities(startDate, endDate),
            dataSubjectRequests: await this.getDataSubjectRequests(startDate, endDate),
            dataBreaches: await this.getDataBreaches(startDate, endDate),
            consentManagement: await this.getConsentMetrics(startDate, endDate),
            dataRetention: await this.getDataRetentionMetrics(startDate, endDate),
            thirdPartyProcessors: await this.getThirdPartyProcessors(),
            privacyImpactAssessments: await this.getPrivacyImpactAssessments(startDate, endDate)
          };
          
          const violations = await this.detectGdprViolations(reportData);
          const recommendations = await this.generateGdprRecommendations(violations);
          
          return ComplianceReport.create({
            framework: ComplianceFramework.GDPR,
            reportType: ReportType.DATA_PROTECTION,
            startDate,
            endDate,
            summary: this.generateReportSummary(reportData),
            findings: reportData,
            violations,
            recommendations,
            status: ReportStatus.DRAFT,
            generatedBy: this.getCurrentUserId()
          });
        }
        
        async generateSoxReport(startDate: Date, endDate: Date): Promise<ComplianceReport> {
          const reportData = {
            accessControls: await this.getAccessControlMetrics(startDate, endDate),
            privilegedAccess: await this.getPrivilegedAccessLogs(startDate, endDate),
            dataChanges: await this.getDataChangeAudits(startDate, endDate),
            systemChanges: await this.getSystemChangeAudits(startDate, endDate),
            financialDataAccess: await this.getFinancialDataAccess(startDate, endDate),
            segregationOfDuties: await this.getSoDViolations(startDate, endDate)
          };
          
          const violations = await this.detectSoxViolations(reportData);
          const recommendations = await this.generateSoxRecommendations(violations);
          
          return ComplianceReport.create({
            framework: ComplianceFramework.SOX,
            reportType: ReportType.AUDIT,
            startDate,
            endDate,
            summary: this.generateReportSummary(reportData),
            findings: reportData,
            violations,
            recommendations,
            status: ReportStatus.DRAFT,
            generatedBy: this.getCurrentUserId()
          });
        }
        
        async scheduleComplianceReports(): Promise<void> {
          const schedules = [
            { framework: ComplianceFramework.GDPR, frequency: 'monthly' },
            { framework: ComplianceFramework.SOX, frequency: 'quarterly' },
            { framework: ComplianceFramework.HIPAA, frequency: 'monthly' }
          ];
          
          for (const schedule of schedules) {
            await this.scheduleReport(schedule.framework, schedule.frequency);
          }
        }
      }
      """
    那么应该生成合规性报告系统:
      """
      {
        "complianceReporting": {
          "gdprReport": {
            "period": "2024-01",
            "summary": {
              "dataSubjects": 15420,
              "dataProcessingActivities": 23,
              "consentRate": 94.2,
              "dataSubjectRequests": 45,
              "dataBreaches": 0,
              "complianceScore": 96.8
            },
            "findings": {
              "dataProcessingActivities": [
                {
                  "activity": "Customer Registration",
                  "legalBasis": "Consent",
                  "dataCategories": ["Personal", "Contact"],
                  "retentionPeriod": "5 years",
                  "thirdPartySharing": false
                }
              ],
              "dataSubjectRequests": {
                "access": 25,
                "rectification": 12,
                "erasure": 8,
                "portability": 0,
                "averageResponseTime": "18 days"
              }
            },
            "violations": [
              {
                "type": "Excessive Privileged Access",
                "description": "User john.doe has maintained admin access for 90+ days",
                "severity": "Medium",
                "remediation": "Review and reduce privileged access duration"
              }
            ],
            "recommendations": [
              "Implement automated privileged access reviews",
              "Enhance segregation of duties controls for financial processes"
            ]
          }
        }
      }
      """
    并且应该支持多种合规框架
    并且应该自动生成报告
    并且应该检测违规行为
    并且应该提供改进建议